const parser = require("xml2json");
const fs = require('node:fs');
const axios = require('axios');
const template = require('./tvxml.json');
const tvIdMap = require('./tvIdMap.json');
const path = require("node:path");

const main = () => {
  axios.get('http://epg.51zmt.top:8000/e.xml')
  .then(res => {
    const xml = res.data;
    if (xml.startsWith('<?xml')) {
      let jObj = JSON.parse(parser.toJson(xml));
      const programme = jObj.tv.programme.filter(i => tvIdMap.some(i2 => i2.val === i.channel));
      template.tv.programme = programme.map(i => {
        const tvId = tvIdMap.find(i2 => i2.val === i.channel);
        let { $t: title } = i.title || {};
        let { $t: desc } = i.desc || {};
        const p = { ...i, channel: tvId.key };
        if (title) {
          p.title = {
            ...i.title,
            $t: title.replace('<', '&lt;').replace('>', '&gt;')
          };
        };
        if (desc) {
          p.desc = {
            ...i.desc,
            $t: desc.replace('<', '&lt;').replace('>', '&gt;')
          };
        }
        return p;
      });

      let tvxml = parser.toXml(template);
      tvxml = `<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE tv SYSTEM "http://api.torrent-tv.ru/xmltv.dtd">` + tvxml;

      fs.writeFileSync(path.resolve(__dirname, '../public/tvxml.xml'), tvxml);
    }
  });
};

module.exports = main;